<template>
  <div>
    <h1>查验模块</h1>
    <center>

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="信息获取" name="first">
        <el-button type="primary" icon="el-icon-search" @click="ObtainResourceClick()">获取资源申请信息</el-button>
        <p></p>
        <center>
          <div style="max-width: 600px">
            <el-table
                :data="tableAnimal"
                v-loading="loading1"
                border
                style="width: 100%"
                :row-class-name="tableRowClassName"
                v-if="tableSeen">
              <el-table-column
                  prop="AnimalID"
                  label="动物编号">
              </el-table-column>
              <el-table-column
                  prop="AnimalName"
                  label="动物名称">
              </el-table-column>
              <el-table-column
                  prop="AnimalNumber"
                  label="动物数量">
              </el-table-column>
            </el-table>

            <el-table
                :data="tableEquipment"
                border
                v-loading="loading2"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                v-if="tableSeen">
              <el-table-column
                  prop="EquipID"
                  label="仪器编号">
              </el-table-column>
              <el-table-column
                  prop="EquipName"
                  label="仪器名称">
              </el-table-column>
              <el-table-column
                  prop="EquipNumber"
                  label="仪器数量">
              </el-table-column>
            </el-table>

            <el-table
                :data="tableAgentia"
                border
                v-loading="loading3"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                v-if="tableSeen">
              <el-table-column
                  prop="AgentiaID"
                  label="药品编号">
              </el-table-column>
              <el-table-column
                  prop="AgentiaName"
                  label="药品名称">
              </el-table-column>
              <el-table-column
                  prop="AgentiaNumber"
                  label="药品数量">
              </el-table-column>
            </el-table>

            <el-table
                :data="tableSample"
                border
                v-loading="loading4"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                v-if="tableSeen">
              <el-table-column
                  prop="SampleID"
                  label="样本编号">
              </el-table-column>
              <el-table-column
                  prop="SampleName"
                  label="样本名称">
              </el-table-column>
              <el-table-column
                  prop="SampleNumber"
                  label="样本数量">
              </el-table-column>
            </el-table>

          </div>
        </center>

      </el-tab-pane>
      <el-tab-pane label="资源查验" name="second">
        <el-form
            ref="form"
            :rules="formRules"
            :inline="true"
            :model="form">
          <el-form-item label="实验编号">
            <el-input size="medium" v-model="form.expid" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="功能单元编号">
            <el-input size="medium" v-model="form.unitid" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="功能单元名称">
            <el-input size="medium" v-model="form.unitname" :disabled="true"></el-input>
          </el-form-item>

          <div v-for="(item, index) in form.dynamicItem" :key="index">
            <el-form-item
                label="类别"
                :prop="'dynamicItem.' + index + '.ResType'"
                :rules="{required: true, message: '类型不能为空', trigger: 'blur'}">
              <el-select v-model="item.ResType" @change="getSelectValue(item,item.ResType)" clearable placeholder="请选择">
                <el-option
                    v-for="item in ResOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
                label="编号"
                :prop="'dynamicItem.' + index + '.ResId'"
                :rules="{required: true, message: '编号不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.ResId"></el-input>
            </el-form-item>
            <el-form-item
                label="名称"
                :prop="'dynamicItem.' + index + '.ResName'"
                :rules="[{required: true, message: '名称不能为空', trigger: 'blur'},]"
            >
              <el-input v-model="item.ResName"></el-input>
            </el-form-item>
            <el-form-item
                label="数量"
                :prop="'dynamicItem.' + index + '.ResNum'"
                :rules="{required: true, message: '数量不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.ResNum" type="number" oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
            </el-form-item>

            <el-form-item>
              <el-popover
                  placement="top"
                  :width="160"
                  v-model:visible="item.visible"
              >
                <p>您确定要删除该记录吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="item.visible = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="item.visible = false,deleteItem(item, index)">确定
                  </el-button>
                </div>
                <template #reference>
                  <el-button type="danger" icon="el-icon-delete" circle @click="item.visible = true"></el-button>
                </template>
              </el-popover>
              <!--              <el-button type="danger" icon="el-icon-delete" circle @click="deleteItem(item, index)"></el-button>-->
            </el-form-item>
          </div>
        </el-form>
        <el-button @click="addItem" type="primary" icon="el-icon-circle-plus-outline">增加查验记录</el-button>
        <el-button type="success" @click="dialogVisible = true" icon="el-icon-circle-check">提交</el-button>
        <el-dialog
            title="提示"
            v-model="dialogVisible"
            width="30%"
            :before-close="handleClose">
          <span>查验信息仅能提交一次，是否确定提交？</span>
          <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitCheckForm()" size="mini">确 定</el-button>
    </span>
          </template>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="状态反馈" name="third">
        <center>
          <div style="max-width: 600px">
            <el-form :model="ruleForm" status-icon :rules="rules" label-position="left" ref="ruleForm"
                     label-width="100px" class="ruleForm">
              <el-form-item label="实验编号">
                <el-input size="medium" v-model="ruleForm.expid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元编号">
                <el-input size="medium" v-model="ruleForm.unitid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元名称">
                <el-input size="medium" v-model="ruleForm.unitname" :disabled="true"></el-input>
              </el-form-item>
              <el-row>
                <el-col span="50">
                  <el-form-item label="功能单元状态">
                    <el-select v-model="ruleForm.unitstate" placeholder="请选择">
                      <el-option-group
                          v-for="group in options"
                          :key="group.label"
                          :label="group.label">
                        <el-option
                            v-for="item in group.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="备注">
                <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="备注"
                    maxlength="100"
                    show-word-limit
                    v-model="ruleForm.textarea">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitStateForm()">提交</el-button>
              </el-form-item>
            </el-form>

          </div>

        </center>

      </el-tab-pane>


    </el-tabs>
    </center>

  </div>
</template>


<script>
import {ref} from "vue";
import {get} from "@/utils/http";
import {ElMessage} from "element-plus";
// import { Alert } from 'element-ui'
// Vue.use(Alert)
// Vue.prototype.$alert = Alert


export default {
  name: "doCheck",
  data() {
    return {
      // activeName: 'first',
      tableAnimal: [],
      tableEquipment: [],
      tableAgentia: [],
      tableSample: [],
      loading1: true,
      loading2: true,
      loading3: true,
      loading4: true,
      checkError: [{
        ErrorResType: '',
        ErrorResId: '',
        ErrorResName: '',
        ErrorResNum: '',
      }],
      dialogVisible: false,
      tableSeen: false,
      isObtained: false,
      ruleForm: {
        expid: '',
        unitid: '',
        unitname: '',
        unitstate: '',
        textarea: ref(''),
      },
      form: {
        expid: 'EXP01',
        unitid: 'UNIT01',
        unitname: 'DNA分离与提纯',
        unitstate: '实验完成',
        textarea: ref(''),
        ResType: '',
        ResId: '',
        ResName: '',
        ResNum: '',
        visible: false,
        dynamicItem: []
      },
      formRules: {
        ResId: [{required: true, message: '请输入编号', trigger: 'blur'}],
        ResName: [{required: true, message: '请输入名称', trigger: 'blur'}],
        ResNum: [{required: true, message: '请输入数量', trigger: 'blur'}]
      },
      ResOptions: [{
        value: 'op1',
        label: '实验动物'
      }, {
        value: 'op2',
        label: '仪器设备'
      }, {
        value: 'op3',
        label: '试剂药品'
      }, {
        value: 'op4',
        label: '生物样本'
      }],
      value: '',
      select: '',
      options: [{
        label: '查验员',
        options: [{
          value: '资源不足',
          label: '资源不足'
        }, {
          value: '查验完成',
          label: '查验完成'
        }]
      }, {
        label: '独立PI',
        options: [{
          value: '实验失败',
          label: '实验失败'
        },]
      },
        {
          label: '科研助理',
          options: [{
            value: '数据有误',
            label: '数据有误'
          }, {
            value: '实验完成',
            label: '实验完成'
          }]
        }],
    };
  },
  created() {
    this.exp_id = this.$route.params.exp_id;
    this.pro_id = this.$route.params.pro_id;
    this.pro_name = this.$route.params.pro_name;
    this.checker_id = this.$route.params.pi_id;
    if (this.exp_id === undefined) {
      this.exp_id = sessionStorage.getItem("exp_id");
    } else {
      sessionStorage.setItem("exp_id", this.exp_id)
    }
    if (this.pro_id === undefined) {
      this.pro_id = sessionStorage.getItem("pro_id");
    } else {
      sessionStorage.setItem("pro_id", this.pro_id)
    }
    if (this.pro_name === undefined) {
      this.pro_name = sessionStorage.getItem("pro_name");
    } else {
      sessionStorage.setItem("pro_name", this.pro_name)
    }
    if (this.checker_id === undefined) {
      this.checker_id = sessionStorage.getItem("pi_id");
    } else {
      sessionStorage.setItem("pi_id", this.checker_id)
    }
    this.ruleForm.expid = this.exp_id;
    this.ruleForm.unitid = this.pro_id;
    this.ruleForm.unitname = this.pro_name;
    this.form.expid = this.exp_id;
    this.form.unitid = this.pro_id;
    this.form.unitname = this.pro_name;
  },

  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    tableRowClassName({row}) {
      if (row.AnimalID) {
        return 'yellow-row';
      }
      if (row.EquipID) {
        return 'blue-row';
      }
      if (row.AgentiaID) {
        return 'green-row';
      }
      if (row.SampleID) {
        return 'purple-row';
      }
    },
    ObtainResourceClick() {  //点击获取资源信息按钮
      let that = this;
      that.tableAnimal = [];
      that.tableEquipment = [];
      that.tableAgentia = [];
      that.tableSample = [];
      get('/funcUnit/getInfo', {
        //todo UN12
        id: that.pro_id
      }).then(function (res) {
            if (res.code === 1) {
              var tmp = {
                equ_info: JSON.parse(res.data.equ_info),
                animal_info: JSON.parse(res.data.animal_info),
                drug_info: JSON.parse(res.data.drug_info),
                sample_info: JSON.parse(res.data.sample_info),
              };
              console.log("tmp.animal_info=??");
              console.log(typeof tmp.animal_info);
              tmp.animal_info.forEach(function (item) {
                console.log(item.name);
                var t = {
                  AnimalID: item.id,
                  AnimalName: item.name,
                  AnimalNumber: item.need_num,
                };
                that.tableAnimal.push(t);
              })
              that.loading1 = false;
              tmp.equ_info.forEach(function (item) {
                console.log(item.name);
                var t = {
                  EquipID: item.id,
                  EquipName: item.name,
                  EquipNumber: item.need_num,
                };
                that.tableEquipment.push(t);
              })
              that.loading2 = false;
              tmp.drug_info.forEach(function (item) {
                console.log(item.name);
                var t = {
                  AgentiaID: item.id,
                  AgentiaName: item.name,
                  AgentiaNumber: item.need_num,
                };
                that.tableAgentia.push(t);
              })
              that.loading3 = false;
              tmp.sample_info.forEach(function (item) {
                console.log(item.name);
                var t = {
                  SampleID: item.id,
                  SampleName: item.name,
                  SampleNumber: item.need_num,
                };
                that.tableSample.push(t);
              })
              that.loading4 = false;
            }
          }
      );
      that.tableSeen = true;
      that.isObtained = true;
    },
    submitForm(formName) {
      let that = this;
      that.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addItem() {
      let that = this;
      that.form.dynamicItem.push({
        ResType: '',
        ResId: '',
        ResName: '',
        ResNum: '',
      })
    },
    deleteItem(item, index) {
      let that = this;
      that.form.dynamicItem.splice(index, 1)
    },

    submitCheckForm() {  //提交查验表单
      let that = this;
      that.checkError = [];
      let flag = false;
      let match = true;
      let exist = false;
      let isChecked = false;
      let errorstr = "";
      let resultStr = '查验完成';
      that.dialogVisible = false;
      get('/proPartialInfo/getInfo', {
        //todo UN12
        exp_id: that.exp_id,
        pro_id: that.pro_id,
        pro_name: that.pro_name,
        pro_state: '',
      }).then(function (res) {
        res.data.forEach(function (item) {
          console.log("22222222222");
          console.log(item.checklog_id);
          if (item.checklog_id > 0) {
            isChecked = true;
            return;
          }
        })
      })

      setTimeout(function () {
            console.log("333333333333");
            console.log(isChecked);
            if (isChecked === true) {
              ElMessage.error({
                showClose: true,
                message: "本单元已提交查验记录，不可重复提交",
                type: "error",
                center: true
              })
              return;
            }

            if (that.isObtained === false) {
              ElMessage.error({
                showClose: true,
                message: "请先至“信息获取”页面获取资源信息！",
                type: "error",
                center: true
              })
              return;
            }

            that.tableAnimal.forEach(function (tmp) {  //需求量
              exist = false;
              that.form.dynamicItem.forEach(function (item) {  //实际获得量
                if (item.ResType === '') {
                  flag = true;
                  return;
                }
                if (item.ResType === 'op1') {
                  if (tmp.AnimalID === item.ResId) {  //在实际获得的资源中有可以匹配的ID
                    exist = true;
                    if (tmp.AnimalName === item.ResName) {
                      if (tmp.AnimalNumber > item.ResNum) {  //需求>供给，缺少
                        var t = {
                          ErrorResType: 'animal',
                          ErrorResId: item.ResId,
                          ErrorResName: item.ResName,
                          ErrorResNum: tmp.AnimalNumber - item.ResNum,  //缺少的数量
                        };
                        that.checkError.push(t);
                      }
                    } else {
                      console.log(tmp.AnimalName);
                      console.log(item.ResName);
                      match = false;
                      return;
                    }
                  }
                }
              })
              if (flag === true)
                return;
              if (match === false)
                return;
              if (exist === false) {
                var t2 = {
                  ErrorResType: 'animal',
                  ErrorResId: tmp.AnimalID,
                  ErrorResName: tmp.AnimalName,
                  ErrorResNum: tmp.AnimalNumber,  //缺少的数量
                };
                that.checkError.push(t2);
              }
            })
            that.tableEquipment.forEach(function (tmp) {  //需求量
              exist = false;
              that.form.dynamicItem.forEach(function (item) {  //实际获得量
                console.log("item=?");
                console.log(item);
                if (item.ResType === '') {
                  flag = true;
                  return;
                }
                if (item.ResType === 'op2') {
                  if (tmp.EquipID === item.ResId) {  //在实际获得的资源中有可以匹配的ID
                    exist = true;
                    if (tmp.EquipName === item.ResName) {
                      if (tmp.EquipNumber > item.ResNum) {  //需求>供给，缺少
                        var t = {
                          ErrorResType: 'equip',
                          ErrorResId: item.ResId,
                          ErrorResName: item.ResName,
                          ErrorResNum: tmp.EquipNumber - item.ResNum,  //缺少的数量
                        };
                        that.checkError.push(t);
                      }
                    } else {
                      console.log(tmp.EquipName);
                      console.log(item.ResName);
                      match = false;
                      return;
                    }
                  }
                }
              })
              if (flag === true)
                return;
              if (match === false)
                return;
              if (exist === false) {
                var t2 = {
                  ErrorResType: 'equip',
                  ErrorResId: tmp.EquipID,
                  ErrorResName: tmp.EquipName,
                  ErrorResNum: tmp.EquipNumber,  //缺少的数量
                };
                that.checkError.push(t2);
              }
            })

            that.tableAgentia.forEach(function (tmp) {  //需求量
              exist = false;
              that.form.dynamicItem.forEach(function (item) {  //实际获得量
                if (item.ResType === '') {
                  flag = true;
                  return;
                }
                if (item.ResType === 'op3') {
                  if (tmp.AgentiaID === item.ResId) {  //在实际获得的资源中有可以匹配的ID
                    exist = true;
                    if (tmp.AgentiaName === item.ResName) {
                      if (tmp.AgentiaNumber > item.ResNum) {  //需求>供给，缺少
                        var t = {
                          ErrorResType: 'agentia',
                          ErrorResId: item.ResId,
                          ErrorResName: item.ResName,
                          ErrorResNum: tmp.AgentiaNumber - item.ResNum,  //缺少的数量
                        };
                        that.checkError.push(t);
                      }
                    } else {
                      match = false;
                      return;
                    }
                  }
                }
              })
              if (flag === true)
                return;
              if (match === false)
                return;
              if (exist === false) {
                var t2 = {
                  ErrorResType: 'agentia',
                  ErrorResId: tmp.AgentiaID,
                  ErrorResName: tmp.AgentiaName,
                  ErrorResNum: tmp.AgentiaNumber,  //缺少的数量
                };
                that.checkError.push(t2);
              }
            })

            that.tableSample.forEach(function (tmp) {  //需求量
              exist = false;
              that.form.dynamicItem.forEach(function (item) {  //实际获得量
                if (item.ResType === '') {
                  flag = true;
                  return;
                }
                if (item.ResType === 'op4') {
                  if (tmp.SampleID === item.ResId) {  //在实际获得的资源中有可以匹配的ID
                    exist = true;
                    if (tmp.SampleName === item.ResName) {
                      if (tmp.SampleNumber > item.ResNum) {  //需求>供给，缺少
                        var t = {
                          ErrorResType: 'sample',
                          ErrorResId: item.ResId,
                          ErrorResName: item.ResName,
                          ErrorResNum: tmp.SampleNumber - item.ResNum,  //缺少的数量
                        };
                        that.checkError.push(t);
                      }
                    } else {
                      match = false;
                      return;
                    }
                  }
                }
              })
              if (flag === true)
                return;
              if (match === false)
                return;
              if (exist === false) {
                var t2 = {
                  ErrorResType: 'sample',
                  ErrorResId: tmp.SampleID,
                  ErrorResName: tmp.SampleName,
                  ErrorResNum: tmp.SampleNumber,  //缺少的数量
                };
                that.checkError.push(t2);
              }
            })
            if (flag === true) {
              ElMessage.error({
                showClose: true,
                message: "请选择资源类型！",
                type: "error",
                center: true
              })
              return;
            }
            if (match === false) {
              ElMessage.error({
                showClose: true,
                message: "编号与名称不匹配！",
                type: "error",
                center: true
              })
              return;
            }
            console.log("checkError[]");
            console.log(that.checkError);
            that.checkError.forEach(function (item) {

              if (item.ErrorResType === 'animal') {
                errorstr = errorstr + ("<p>缺少动物：" + item.ErrorResName + "&nbsp&nbsp&nbsp数量：" + item.ErrorResNum + "</p>");
              } else if (item.ErrorResType === 'equip') {
                errorstr = errorstr + ("<p>缺少仪器：" + item.ErrorResName + "&nbsp&nbsp&nbsp数量：" + item.ErrorResNum + "</p>");
              } else if (item.ErrorResType === 'agentia') {
                errorstr = errorstr + ("<p>缺少药品：" + item.ErrorResName + "&nbsp&nbsp&nbsp数量：" + item.ErrorResNum + "</p>");
              } else if (item.ErrorResType === 'sample') {
                errorstr = errorstr + ("<p>缺少样本：" + item.ErrorResName + "&nbsp&nbsp&nbsp数量：" + item.ErrorResNum + "</p>");
              }
            })
            console.log("errorstr" + errorstr);
            that.$alert(errorstr, '查验结果', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true
            });
            if (that.checkError.length !== 0) {
              resultStr = '资源不足';
            }
            let now = new Date();
            console.log(now);
            var year = now.getFullYear(); //得到年份
            var month = now.getMonth();//得到月份
            var date = now.getDate();//得到日期
            var hour = now.getHours();//得到日期
            var minute = now.getMinutes();//得到日期
            var second = now.getSeconds();//得到日期
            console.log(typeof month);
            console.log(date);
            month = month + 1;
            if (month < 10) month = "0" + month;
            if (date < 10) date = "0" + date;
            if (hour < 10) hour = "0" + hour;
            if (minute < 10) minute = "0" + minute;
            if (second < 10) second = "0" + second;
            var nowStr = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;    //（格式化"yyyy-MM-dd"）
            // var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
            console.log(nowStr);

            get('/checkLog/record', {
              checklog_id: year.toString() + month + date + hour + minute + second,
              //todo checker_id
              checker_id: 'CK' + that.checker_id,
              check_time: nowStr,
              check_result: resultStr,
            }).then(function (ans) {
              console.log(ans);
            })
            setTimeout(function () {
              get('/proPartialInfo/updateCheckLog', {
                //todo UN12
                pro_id: that.pro_id,
                checklog_id: year.toString() + month + date + hour + minute + second,
              }).then(function (ans) {
                console.log(ans);
              })
            }, 300);

          }, 500
      )

    },
    submitStateForm() {
      let that = this;
      console.log(that.ruleForm.unitstate);
      if (that.ruleForm.unitstate === '') {
        ElMessage.error({
          showClose: true,
          message: "请选择功能单元状态！",
          type: "error",
          center: true
        })
        return;
      }
      if (that.ruleForm.unitstate === '实验失败' || that.ruleForm.unitstate === '数据有误' || that.ruleForm.unitstate === '实验完成') {
        ElMessage.warning({
          showClose: true,
          message: "您没有权限提交此类信息",
          type: "warning",
          center: true
        })
        return;
      } else {
        get('/proPartialInfo/updateState', {
          exp_id: that.ruleForm.expid,
          pro_id: that.ruleForm.unitid,
          pro_state: that.ruleForm.unitstate,
          other_info: that.ruleForm.textarea
        }).then(function (res) {
          if (res.code === 1) {
            ElMessage.success({
              showClose: true,
              message: "状态更新成功！",
              type: "success",
              center: true
            })
          } else {
            ElMessage.warning({
              showClose: true,
              message: "状态更新失败,未能找到相应记录!",
              type: "warning",
              center: true
            })
          }

        })

      }
    },
    getSelectValue(item, value) {
      item.ResType = value;
    },
  }
}
</script>

<style>
.el-table .yellow-row {
  background: oldlace;
}

.el-table .green-row {
  background: #f0f9eb;
}

.el-table .purple-row {
  background: #F4EEFF;
}

.el-table .blue-row {
  background: #EBF5FF;
}
</style>